package com.bawei.arouter

import android.content.Context
import com.alibaba.android.arouter.facade.Postcard
import com.alibaba.android.arouter.facade.annotation.Interceptor
import com.alibaba.android.arouter.facade.callback.InterceptorCallback
import com.alibaba.android.arouter.facade.template.IInterceptor
import com.tencent.mmkv.MMKV

/**
 * Author: Jason Zhang
 * Date: 2024/4/26
 * Desc: 路由参数拦截器
 */
@Interceptor(priority = 4, name = "路由参数拦截器")
class RouteParamsInterceptor : IInterceptor{

    private lateinit var mContext: Context

    //白名单集合
    private val checkPaths = arrayOf("/activity/main", "/activity/detail")

    override fun init(context: Context?) {
        if (context != null) {
            mContext = context
        }
    }

    override fun process(postcard: Postcard, callback: InterceptorCallback) {
        try {
            val routePath = postcard.path
            val sessionId = MMKV.defaultMMKV().decodeString("sessionId", "123")
            //获取Router携带参数
            val params = postcard.extras
            //检查是否存在白名单中
            if(checkPaths.contains(routePath) && !params.containsKey("sessionId")){
                postcard.withString("sessionId", sessionId)
            }
            //最后要释放，页面的跳转逻辑继续执行
            callback.onContinue(postcard)
        } catch (e: Exception) {
            e.printStackTrace()
            callback.onContinue(postcard)
        }
    }

}